import { FC, useEffect, useRef } from 'react'
import { bindOptions, getOptions } from './options'
import { useSetState } from 'ahooks'
import * as echarts from 'echarts'
import { debounce } from 'lodash'
import axios from 'axios'

const MapPage: FC = () => {
  const chartRef = useRef<HTMLDivElement | null>(null)
  const currentCity = 'china'
  let chart: echarts.ECharts | null = null
  const [state, setState] = useSetState<any>({
    mapData: [], // 地图上的数据，比如某些数据点
    mapName: '', // 当前城市名字
  })

  const geoJson = useRef<any>({}) // 请求json地图返回的geo数据

  // 防抖，300ms内只响应最后一次
  const debouncedFn = debounce(() => {
    resize()
  }, 500)

  useEffect(() => {
    getMapJson()
  }, [])

  useEffect(() => {
    window.addEventListener('resize', debouncedFn)

    return () => {
      if (!chart) {
        return
      }

      window.removeEventListener('resize', resize)
      chart && chart.dispose()
      chart = null
    }
  }, [])

  // 响应resize
  function resize() {
    chart?.resize()
  }

  // 初始化chart
  function initChart() {
    echarts.registerMap(currentCity, geoJson.current)

    const chartInstance = echarts.getInstanceByDom(chartRef.current as any)
    chart = chartInstance || echarts.init(chartRef.current as any, 'dark')
    chart.setOption(bindOptions(currentCity) as any)
    chart.showLoading()
  }

  // 注册地图
  const registerMap = (currentMap: any) => {
    if (!chart) {
      return
    }

    setState({ mapName: currentMap.name })

    const mapName = currentMap.name
    const features: any[] = geoJson.current.features.filter((item: any) => {
      if (item.properties.name === currentMap.name) {
        return item
      }
    })

    echarts.registerMap(mapName, { features } as any)

    const option: any = getOptions(mapName, state.mapData)

    chart.clear()
    chart.setOption(option)
  }

  // 绑定下钻事件
  const bindMap = () => {
    if (!chart) {
      return
    }

    chart.off('click').on('click', (currentMap: any) => {
      if (currentMap.componentSubType === 'effectScatter') {
        return
      }

      registerMap(currentMap)
    })
  }

  // 获取map
  const getMapJson = () => {
    const mapApiUrl = import.meta.env.VITE_MAP_API_URL
    const url = `${mapApiUrl}/map/province/${currentCity}.json`

    axios({ url }).then(({ data }: any) => {
      setState({ mapName: '' })
      geoJson.current = data
      initChart()
      bindMap()
      chart && chart.hideLoading()
    })
  }

  // 点击返回
  const onBackMap = () => {
    initChart()
    bindMap()
    chart && chart.hideLoading()
    setState({ mapName: '' })
  }

  return (
    <div className="app-page-map relative">
      <div className="app-map-back">
        <h2 className="lum-char" onClick={onBackMap}>
          {!state.mapName ? (<span className="back-chart">{ currentCity.toUpperCase() }</span>) : (<span>{ state.mapName }</span>)}
          {state.mapName && (
            <>
              <span className="ant-breadcrumb-separator">|</span>
              <span>点击返回</span>
            </>
          )}
        </h2>
      </div>
      <div ref={chartRef} id="chart" className="app-line-chart" style={{ width: 'calc(100vw - 240px)', height: 'calc(100vh - 145px)' }}> </div>
    </div>
  )
}

export default MapPage
